import { RuleDao } from "@/dao/ruleDao"
import { TaskDao } from "@/dao/taskDao"
import { ArticleDao } from "@/dao/articleDao"
import { ArticleStatus, UsageScope } from "@/entities/Constant"

async function startAi(article, page) {
    try {
        let whereDict = {
            enable: 1,
            usageScope: UsageScope.Ai
        }
        let tasks = await TaskDao.fetchAll(whereDict)
        let err = null
        for (let task of tasks) {
            let rule = await RuleDao.fetchById(task.ruleId)
            console.log("rule", rule)
            let aiFns = require('./' + rule.module)
            let res = await aiFns.goAi(page, task, article, rule)
            err = res.err
            if (!res.err) {
                article.aiResult = res.data
                break
            }
        }
        if (err) {
            return { err: err }
        }
        article.status = ArticleStatus.Aigced
        let res = await ArticleDao.save(article)
        if (!res) {
            return { err: "保存文章错误" }
        }
        return { err: null }
    } catch (err) {
        return { err: err }
    }
}

export { startAi }